//
//  MyIntegralViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/4.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "MyIntegralViewController.h"

#import "MyIntegralCell.h"

@interface MyIntegralViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UILabel *allIntegral;
@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic,strong)  NSMutableArray  * dataArray;

@property (nonatomic,assign)  NSInteger       page;
@property (nonatomic,assign)  NSInteger       current_page;

@end

@implementation MyIntegralViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, -STATUS_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT + STATUS_BAR_HEIGHT)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.rowHeight = ScreenX375(56);
    [self.view addSubview:self.tableView];
    
    [self setHead];
    
    [self refreshTableView];
}

- (void)setHead {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(170) + STATUS_BAR_HEIGHT)];
    _tableView.tableHeaderView = headView;
    
    UIImageView *bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(170) + STATUS_BAR_HEIGHT)];
    bgView.image = [UIImage imageNamed:@"背景"];
    [headView addSubview:bgView];
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, STATUS_BAR_HEIGHT, NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT, NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT)];
    [backBtn setImage:[UIImage imageNamed:@"返回白色"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:backBtn];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(60), STATUS_BAR_HEIGHT, SCREEN_WIDTH - ScreenX375(120), NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT)];
    titleLabel.text = @"积分";
    titleLabel.font = Kfont(16);
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:titleLabel];
    
    _allIntegral = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenX375(60) + STATUS_BAR_HEIGHT, SCREEN_WIDTH, ScreenX375(44))];
    _allIntegral.font = Kfont(30);
    _allIntegral.textAlignment = NSTextAlignmentCenter;
    _allIntegral.textColor = [UIColor whiteColor];
    [headView addSubview:_allIntegral];
    
    UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenX375(130) + STATUS_BAR_HEIGHT, SCREEN_WIDTH, ScreenX375(20))];
    noteLabel.font = Kfont(14);
    noteLabel.textAlignment = NSTextAlignmentCenter;
    noteLabel.text = @"当前积分";
    noteLabel.textColor = [UIColor whiteColor];
    [headView addSubview:noteLabel];
}

- (void)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)refreshTableView
{
    /** 为了避免 block 的循环引用导致内存泄漏  要使用__weakSelf 来代替self */
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.current_page = 1;
        [weakSelf requestData];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf requestMoreData];
    }];
    [self.tableView.mj_header beginRefreshing];
}

-(void)requestData
{
    NSString *url = [NSString stringWithFormat:@"%@app/integral_record",REQUESTHEADER];
    NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken],@"page":@"1"};
    
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [self.tableView.mj_header endRefreshing];
            NSError *error;
            
            [self.dataArray removeAllObjects];
            self.allIntegral.text = [NSString stringWithFormat:@"%@",successResponse[@"user"][@"integral"]];
            self.page = [successResponse[@"data"][@"last_page"] integerValue];
            // 成功
            for (NSDictionary *dic in successResponse[@"data"][@"data"]) {
                IntegralModel *model = [[IntegralModel alloc] initWithDictionary:dic error:&error];
                if (model != nil) {
                    [self.dataArray addObject:model];
                }
            }
            [self.tableView reloadData];
            
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [self.tableView.mj_header endRefreshing];
        [HttpManager showFail];
    }];
}

-(void)requestMoreData
{
    self.current_page++;
    NSString *url = [NSString stringWithFormat:@"%@app/integral_record",REQUESTHEADER];
    NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken],@"page":[NSNumber numberWithInteger:self.current_page]};
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [self.tableView.mj_footer endRefreshing];
            NSError *error;
            // 成功
            self.allIntegral.text = [NSString stringWithFormat:@"%@",successResponse[@"user"][@"integral"]];
            self.page = [successResponse[@"data"][@"last_page"] integerValue];
            // 成功
            for (NSDictionary *dic in successResponse[@"data"][@"data"]) {
                IntegralModel *model = [[IntegralModel alloc] initWithDictionary:dic error:&error];
                if (model != nil) {
                    [self.dataArray addObject:model];
                }
            }
            [self.tableView reloadData];
            
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [self.tableView.mj_footer endRefreshing];
        [HttpManager showFail];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyIntegralCell *cell = [MyIntegralCell cellWithTableView:tableView andIndexPath:indexPath];
    cell.integralModel = _dataArray[indexPath.row];
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
